import cv2

def move_check(front_mat, after_mat):
    front_gray = cv2.cvtColor(front_mat, cv2.COLOR_BGR2GRAY)
    after_gray = cv2.cvtColor(after_mat, cv2.COLOR_BGR2GRAY)

    diff_gray = cv2.absdiff(front_gray, after_gray)
    _, diff_gray = cv2.threshold(diff_gray, 25, 255, cv2.THRESH_BINARY)

    element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    diff_gray = cv2.erode(diff_gray, element)

    element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20))
    diff_gray = cv2.dilate(diff_gray, element2)

    contours, _ = cv2.findContours(diff_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    resframe = after_mat.copy()
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(resframe, (x, y), (x + w, y + h), (0, 255, 0), 4)

    return resframe, contours

# 打开原始视频文件
cap = cv2.VideoCapture("output2.avi")
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

# 创建视频写入对象
out = cv2.VideoWriter('output3.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (frame_width, frame_height))

count = 0
tempframe = None
while True:
    ret, frame = cap.read()
    if not ret:
        break

    if count == 0:
        res,contours = move_check(frame, frame)
        tempframe = frame.copy()

    else:
        res,contours = move_check(tempframe, frame)
        tempframe = frame.copy()

    
    if len(contours) <= 1:
        out.write(frame)
        cv2.imshow("res", res)
        print(f"Detected {len(contours)} boxes in the frame.")  # 打印检测到的框框数量
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break
    # 如果当前帧中框框数小于或等于1，则写入新视频
    count += 1


cap.release()
out.release()
cv2.destroyAllWindows()